﻿using System;
using System.Collections.Generic;
using System.Text;
using Fsb.Utility;
using VideoCache.Aggregation.Interfaces;

namespace VideoCache.Aggregation.Implements
{
    [Site("tudou.com")]
    [Site("tudouui.com")]
    class TudouFetcher
    {
        public string GetToken(string url)
        {
            string token = this.GetTokenByUrl(url);

            if (string.IsNullOrEmpty(token))
            {
                return this.GetTokenByPlayer(url);
            }

            return token;
        }

        private string GetTokenByUrl(string url)
        {
            string html = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));

            string iid = StringUtility.SubString(html, "iid:", ",").Trim();

            return iid;
        }

        private string GetTokenByPlayer(string url)
        {
            // http://js.tudouui.com/bin/lingtong/PortalPlayer_29.swf?listType=4&listCode=3cGInKspGAE&icode=zNWxk5CmwNs&iid=130971603&lid=0&aid=177122&uid=0&sp=http://g1.ykimg.com/0100641F46516DE807B63D0855F5CFD763C701-8568-2245-12A5-8B3D0E6FAE7A&tvcCode=-1&channel=31&cs=457|461&k=音乐|真人秀&tict=2&prd=新娱乐传媒有限公司,韩国CJE&M娱乐公司&default_skin=0&tudouMini=0&hd=3&ol=0&olw=-1&olh=-1&olr=-1&lb=0&referrer=http%3A%2F%2Fwww.tudou.com%2F&href=http%3A%2F%2Fwww.tudou.com%2Falbumplay%2F3cGInKspGAE%2FzNWxk5CmwNs.html&USER_AGENT=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22&kw=%E5%A6%88%E5%A6%88%E5%92%AA%E5%91%80%20130416&title=%E5%A6%88%E5%A6%88%E5%92%AA%E5%91%80%20130416&mediaType=vi&ports=100:0&statratio=1000&safekey=IAlsoNeverKnow&ct=180&ca=0&cb=0.1&ctime=5000&cp=20&juid=017nh25cfq31hh&seid=017ob9hgs26ts&aop=0&np=0&sh=0.0000&st=0.0000&videoOwner=113077370&cdnType=2&time=4475&yjuid=&yseid=1366178710398TXz3xa&ypvid=1366178793462FRrh9A&yrpvid=1366178737082TMsE0O&yrct=31&frame=0&noCookie=0&yseidtimeout=1366185993463&yseidcount=1&actionID=0&ID=0&adOwnerId=0&adPositionId=0&isNielson=0&isRenhe=0&vurl=&phd=-1&rurlstr=&resourceId=&rinfo=&tpa=&pepper=http://css.tudouui.com/bin/binder/pepper_3.png&panelEnd=http://css.tudouui.com/bin/lingtong/PanelEnd_5.swz&panelRecm=http://css.tudouui.com/bin/lingtong/PanelRecm_5.swz&panelShare=http://css.tudouui.com/bin/lingtong/PanelShare_4.swz&panelCloud=http://css.tudouui.com/bin/lingtong/PanelCloud_4.swz&youkuId=XNTQzOTQ1MzAw&vcode=XNTQzOTQ1MzAw&ymulti=&wtime=9&scale=1

            return UrlHelper.GetParameter(url, "iid");
        }
    }
}